package com.juyu.miliao.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.dao.mysql.UserLoginDao;
import com.juyu.miliao.api.service.MinorModeService;
import com.juyu.miliao.api.service.UserAuthenticationInfoService;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.VerifyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 *  未成年模式
 * @Auther: 卜加超
 * @Date: 2019/5/21 14:31
 * @Description:
 */
@RestController
@RequestMapping("minorMode")
public class MinorModeController {
    private static final Logger logger = LoggerFactory.getLogger(MinorModeController.class);
    private String phoneRegex="^[0-9]{11}$";
    @Resource
    private MinorModeService minorModeService;
    @PostMapping("/")
    public JSONObject getMinorMode(Authentication token){
        Subject subject = (Subject) token.getPrincipal();
       return  minorModeService.getMinorMode(subject.getId());
    }
    /**
     * 设置未成年人模式密码
     * @param userId
     * @param password
     */
    @GetMapping("/{userId}-{password}")
    public void addMinorModePassword(@PathVariable("userId") long userId,@PathVariable("password") String password){
        minorModeService.addMinorModeForPassword(userId,password);

    }

    /**
     * 关闭未成年人模式
     * @param userId
     * @param password
     * @return
     */
    @GetMapping("/login/{userId}-{password}")
    public void checkMinorModePassword(@PathVariable("userId") long userId,
                                             @PathVariable("password") String password){
        minorModeService.checkMinorModePassword(userId,password);
    }

    /**
     * 发送验证码
     */
    @PostMapping("/phone")
    public void sendPhoneNumVerificationCode(HttpServletRequest request, Authentication token, String phone) {
        if (phone == null || !phone.matches(phoneRegex)) {
            throw new ConsumeRuntimeException("手机号格式不正确");
        }
        CommonHead com = VerifyUtil.verifyCommonHead(request);
        Subject subject = (Subject) token.getPrincipal();
        minorModeService.sendPhoneCode(subject.getId(),phone,com);

    }

    /**
     * 解锁未成年模式（忘记密码）
     * @param token
     * @param phone
     * @param code
     */
    @PostMapping("/bind")
    public void unlockMinorMode(Authentication token,@RequestParam String phone,@RequestParam String code){
        Subject subject = (Subject) token.getPrincipal();
        minorModeService.unlockMinorMode(subject.getId(),phone,code,subject.getIsHost());
    }

}
